/*
 * {comment of class}
 *
 * @author (C) <a href="http://www.carfield.com.hk">Carfield Yim </a>, 2004
 */
package hk.com.carfield.util;

import hk.com.carfield.core.ContentManager;
import hk.com.carfield.item.FileItem;
import hk.com.carfield.item.HeadItem;
import hk.com.carfield.item.Item;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.io.IOUtils;
import org.jdom.Verifier;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;

public final class StringUtil {
	public static final String HTML_LINE_BREAK = "<br/>";

	public static String code2html(final InputStream source) throws IOException {
		final String str = "<pre class=\"jsccJAVA\">"
				+ IOUtils.toString(source) + "</pre>";
		source.close();
		return str;
	}

	public static boolean getBoolean(final String value) {
		return value != null && value.equalsIgnoreCase("true");
	}

	public static String getExtensions(final String fileName) {
		final int MAX_EXTENSION_LENGTH = ContentManager.COMMENT.length() + 1;
		final int extIndex = fileName.lastIndexOf('.');
		if (extIndex > 0 && fileName.length() > extIndex + 1) {
			final String extension = StringUtil.safeSubString(fileName,
					extIndex + 1, fileName.length());
			if (extension.length() < MAX_EXTENSION_LENGTH) {
				return extension;
			}
		}
		return "";
	}

	public static boolean notBlank(final String s) {
		return s != null && !s.trim().equals("") && !s.equals("null");
	}

	public static String safeSubString(final String str, int startIndex,
			int endIndex) {
		if (startIndex > endIndex) {
			return "";
		}
		if (str == null) {
			return "";
		}
		if (str.length() < startIndex) {
			startIndex = 0;
		}
		if (str.length() < endIndex) {
			endIndex = str.length();
		}
		return str.substring(startIndex, endIndex);
	}

	public static String text2Html(final Reader r) throws IOException {
		return StringUtil.text2Html(r, StringUtil.HTML_LINE_BREAK);
	}

	public static String text2Html(final Reader r, final String lineBreak)
			throws IOException {
		if (lineBreak == null) {
			return StringUtil.text2Html(r);
		}
		final BufferedReader buf = new BufferedReader(r);
		final StringBuffer sb1;
		try {
			String line;
			sb1 = new StringBuffer();
			while ((line = buf.readLine()) != null) {
				// TODO improve link handling
				// TODO Indented source code will be formatted with <pre> tags.
				if (line.indexOf("://") > 0) {
					final StringTokenizer st = new StringTokenizer(line, " ");
					final StringBuffer sb2 = new StringBuffer(line.length());
					while (st.hasMoreTokens()) {
						final String s = st.nextToken();
						if (s.indexOf("://") > 0 && s.indexOf("\"") < 0) {
							final String linkLabel;
							// TODO from freshmeat, seem 65 look good, may
							// related to session
							if (s.length() > 65) {
								// Lenght of http://_ is 8
								final int slashIndexAfterProtocolSlash = s
										.indexOf("/", 8);
								final String domain = StringUtil.safeSubString(
										s, 0, slashIndexAfterProtocolSlash);
								final String ending = StringUtil.safeSubString(
										s, s.length() - 40, s.length());
								linkLabel = domain + "[..]" + ending;
							} else {
								linkLabel = s;
							}
							sb2.append("<a href=\"").append(s).append("\">")
									.append(linkLabel).append("</a>")
									.append(" ");
						} else {
							sb2.append(s).append(" ");
						}
					}
					sb1.append(sb2).append(lineBreak);
				} else {
					sb1.append(line).append(lineBreak);
				}
			}
		} finally {
			buf.close();
		}
		return sb1.toString();
	}

	// TODO special handling for image
	public static SyndFeed writeXML(final String host, final Item head,
			final Writer writer) throws IOException, FeedException {
		final SyndFeed feed = new SyndFeedImpl();
		feed.setFeedType("atom_1.0");
		feed.setTitle(host);
		feed.setLink(head.getUrl());
		feed.setDescription(head.getDesc());

		final List<SyndEntry> entries = new ArrayList<SyndEntry>();
		for (final Item item : head.getChildren()) {
			final SyndEntry entry = new SyndEntryImpl();
			entry.setTitle(item.getName());
			entry.setLink(item.getUrl());
			entry.setPublishedDate(item.getDate());
			final SyndContent description = new SyndContentImpl();
			description.setType("text/html");
			final String tempText;
			final StringBuilder content = new StringBuilder();
			if (item instanceof FileItem) {
				tempText = HeadItem.extendedDesc((FileItem) item);
			} else {
				tempText = item.getDesc();
			}

			/* from JDOM library... */
			/* 159 */int i = 0;
			for (final int len = tempText.length(); i < len; ++i)
			/*      */{
				/* 161 */final char ch = tempText.charAt(i);
				/* 164 */if (Verifier.isHighSurrogate(ch))
				/*      */{
					/* 166 */++i;
					/* 167 */if (i < len) {
						/* 168 */final char low = tempText.charAt(i);
						/* 169 */if (!Verifier.isLowSurrogate(low)) {
							/* 170 */continue;
							/*      */}
						/*      */}
					/*      */else {
						/* 177 */continue;
						/*      */}
					/*      */}
				/* 181 */if (!Verifier.isXMLCharacter(ch))
				/*      */{
					/* 185 */continue;
					/*      */}
				/*      */content.append(ch);
				/*      */}
			/*      */

			description.setValue(content.toString());
			entry.setDescription(description);
			entries.add(entry);
		}
		feed.setEntries(entries);

		final SyndFeedOutput output = new SyndFeedOutput();
		output.output(feed, writer);
		return feed;
	}
}